<template>
  <div>
    <ItemHeader :menuArr="categoryArr" @navFn="selectThis">
      <span slot="leftBtn">
        <a href="javascript:void(0)" @click="showSetPaymentBox()" class="fr">提问设置</a>
      </span>
    </ItemHeader>
    <div>
      <div v-for="(qaData, index) in anwserListDataArr" :key="qaData.key" v-show="index===currentCategoryIndex">
        <QaItem :list="qaData.list" :categoryTypeIndex="index" @showAnswerQuestionBoxFn="showAnswerQuestionBox" />
        <button v-if="anwserListDataArr[currentCategoryIndex].total > anwserListDataArr[currentCategoryIndex].list.length" class="load-more-btns small-one ftz16" @click="loadMore">
          <template v-if="anwserListDataArr[currentCategoryIndex].isLoadingMore">
            <i class='layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop ftz20'></i>
            <span>正在加载，请稍候......</span>
          </template>
          <span v-else>点击加载更多...</span>
        </button>
      </div>
    </div>
    <!-- 回复问题 -->
    <MessageBox v-show="answerQuestionBoxFlag" @closeFn="closeAnswerQuestionBox" :info="{height: 324, width: 548, title: '回复问题'}">
      <div slot="main">
        <div class="ans-c">
          <div class="txt" id="txt">
            <textarea maxlength="120" placeholder="输入您的精彩回答，您将获得更多关注和奖励" v-model="answerContent"></textarea>
            <span class="num">
              <i num="">{{answerContent.length}}</i>/120</span>
          </div>
          <div class="tip">说明：除了提问人之外，其他人查看您的回答，如果是免费的，所有人均可查看；如果是付费的，需要解锁回答才能查看，解锁金额是提问金额的50%</div>
          <button class="sub-btn" :class="{'on': answerContent.length >= 20}" @click="doSubmit()">回答</button>
        </div>
      </div>
    </MessageBox>
    <!-- 提问设置 -->
    <MessageBox v-show="setPymentBoxFlag" @closeFn="closeSetPaymentBox" :info="{height: 300, width: 454, title: '提问设置'}">
      <div slot="main">
        <div class="quiz-c">
          <div class='set' id='set'>
            <div class="item-set">
              <input type='radio' name='set' id="free-payment" v-model="isFree" value='true' title='免费提问'>
              <label for="free-payment">免费提问</label>
            </div>
            <div class="item-set">
              <input type='radio' name='set' id="charge-payment" v-model="isFree" value='false' title='付费提问'>
              <label for="charge-payment">付费提问</label>
            </div>
          </div>
          <div class='price'>
            <input type='number' placeholder='0.0' id='price' class='pay' min="0" step="0.01" :disabled="isFree===true" v-model="myCharge" :class="{'disabled': isFree===true}">
            <span>中亿币</span>
          </div>
          <div class='sub-btn' id='sub_btn'>
            <button @click="closeSetPaymentBox()" type='button'>取消</button>
            <button class='red' @click="submitMyCharge()" type='button'>确定</button>
          </div>
          <div class='tip'>说明：除了提问人之外，其他人查看您的回答，如果是免费的，所有人均可查看；如果是付费的，需要解锁回答才能查看，解锁金额是提问金额的50%</div>
        </div>
      </div>
    </MessageBox>
  </div>
</template>
<script>
import ItemHeader from '@/components/dashboardAuth/item-header'
import MessageBox from '@/components/message-box'
import QaItem from '@/components/dashboardAuth/qa-item'
import { mapState } from 'vuex'
import {
  getMyReceivedQuestion,
  answerQuestion,
  getRaiseQuestion,
  setMyAnswereCharge,
  getUserInfoForRaisingQuestion
} from '@/service/api'
export default {
  components: {
    ItemHeader,
    MessageBox,
    QaItem
  },
  watch: {
    isFree (newVal, oldVal) {
      if (JSON.parse(newVal)) {
        this.myCharge = 0
      }
    }
  },
  computed: {
    userId () {
      return this.$store.state.me.sysUser.userId
    },
    ...mapState({
      me: state => state.me || {}
    })
  },
  data () {
    return {
      anwserListDataArr: [],
      searchDataArr: [],
      // categoryArr: ['全部', '待回答', '已回答', '我的提问'],
      categoryArr: [{ name: '全部', route: '/dashboardAuth/answer' }, { name: '待回答', route: '/dashboardAuth/answer' }, { name: '已回答', route: '/dashboardAuth/answer' }, { name: '我的提问', route: '/dashboardAuth/answer' }],
      currentCategoryIndex: 0,
      layerLoad: false,
      toAnswerQuestionId: 0,
      answerQuestionBoxFlag: false,
      // 回答的内容
      answerContent: '',
      setPymentBoxFlag: false,
      isFree: true,
      myCharge: 0,
      // 提问的大咖
      targetMasterInfo: {
        id: '',
        name: '',
        avatar: '',
        comment: '',
        field: '',
        fieldId: '',
        answerCount: '',
        answerPay: ''
      },
      submitting: false // 数据提交中
    }
  },
  mounted () {
    this.$nextTick(() => {
      if (window.layer) {
        this.showLoadingModal()
      }
      this.initAnwserListDataArr()
      this.initData()
    })
  },
  methods: {
    showLoadingModal () {
      this.layerLoad = window.layer.load(0, {
        shade: false
      })
    },
    closeLoadingModal () {
      if (window.layer) {
        window.layer.close(this.layerLoad)
      }
    },
    initData () {
      let fn = this.getMyAnswerList
      if (this.currentCategoryIndex > 2) {
        fn = this.getMyAnwseredQuestionList
      }
      fn().then((res) => {
        if (res.status === 200) {
          this.anwserListDataArr[this.currentCategoryIndex].list = res.data.list
          this.anwserListDataArr[this.currentCategoryIndex].total = res.data.total
          this.anwserListDataArr[this.currentCategoryIndex].loaded = true // 数据已经请求过
          this.closeLoadingModal()
        }
      })
    },
    selectThis (index) {
      this.currentCategoryIndex = index
      if (!this.anwserListDataArr[this.currentCategoryIndex].loaded) {
        this.showLoadingModal()
        this.initData()
      }
    },
    /*
     * status 值如下
     *  DELETED("-1","已删除"),
        NOT_PAID("0","未支付"),
        VERITING("3","待审核"),
        VERITY_FAILD("5","审核失败"),
        WAITING_ANSWER("10","待回答"),
        ANSWERED("20","已回答"),
        EXPIRED("30","已失效")
    */
    initAnwserListDataArr () {
      for (let i = 0; i < this.categoryArr.length; i++) {
        let searchObj = {
          pageSize: 6,
          pageNum: 1,
          status: ['', '10', '20', ''][i]
        }
        // 查询全部是多一个参数
        if (i === 0) {
          searchObj.answerAll = 1
        }
        this.searchDataArr.push(searchObj)
        this.anwserListDataArr.push({
          key: i,
          total: 0,
          list: [],
          isLoadingMore: false,
          loaded: false
        })
      }
    },
    loadMore () {
      let index = this.currentCategoryIndex
      this.anwserListDataArr[index].isLoadingMore = true
      this.searchDataArr[index].pageNum++

      // 区分调用的接口
      let fn = this.getMyAnswerList
      if (this.currentCategoryIndex > 2) {
        fn = this.getMyAnwseredQuestionList
      }
      fn().then((res) => {
        this.anwserListDataArr[index].isLoadingMore = false
        if (res.status === 200) {
          this.anwserListDataArr[this.currentCategoryIndex].list.push(...res.data.list)
        } else {
          this.searchDataArr[index].pageNum.pageNum--
        }
      })
    },
    // 我收到的问题列表
    async getMyAnswerList () {
      let searchData = this.searchDataArr[this.currentCategoryIndex]
      let res = await getMyReceivedQuestion(searchData)
      return res
    },
    // 大咖的提问信息
    // 获取投顾的提问所需的基本信息。
    initUserInfoForRaisingQuestion () {
      getUserInfoForRaisingQuestion({ userId: this.me.sysUser.userId }).then(res => {
        if (res && res.data) {
          if (!res.data.answerPay) {
            this.myCharge = 0
            this.isFree = true
          } else {
            this.myCharge = res.data.answerPay
            this.isFree = false
          }
        }
      })
    },
    // 我已经回答的问题列表
    async getMyAnwseredQuestionList () {
      let searchData = this.searchDataArr[this.currentCategoryIndex]
      let res = await getRaiseQuestion(searchData)
      return res
    },
    showAnswerQuestionBox (id) {
      this.toAnswerQuestionId = id
      this.answerQuestionBoxFlag = true
    },
    closeAnswerQuestionBox () {
      this.answerQuestionBoxFlag = false
    },
    // 回答问题
    async doSubmit () {
      if (this.submitting) {
        this.showMsgTip('回答内容提交中……')
        return
      }
      if (this.answerContent.length < 20) {
        this.showMsgTip('回答内容不能少于20个字')
        return
      }
      this.submitting = true
      this.showLoadingModal()
      const info = {
        questionId: this.toAnswerQuestionId,
        answerContent: this.answerContent,
        nameShowable: 0,
        countStar: 0
      }
      let res = await answerQuestion(info)
      this.submitting = false
      this.closeLoadingModal()
      if (res.data) {
        this.showMsgTip('回答成功')
        this.closeAnswerQuestionBox()
        this.updateList(this.answerContent)
        this.answerContent = ''
      } else {
        this.showMsgTip('回答失败')
      }
    },
    getIndexInList (list) {
      let index = list.findIndex((item) => {
        return item.question.questionId === this.toAnswerQuestionId
      })
      return index
    },
    // 更新列表
    updateList (content) {
      // 更新“全部”列表
      let index = this.getIndexInList(this.anwserListDataArr[0].list)
      let item = this.anwserListDataArr[0].list[index]
      item.question.status = '20'
      item.answerShort = content
      this.$set(this.anwserListDataArr[0].list, index, item)

      // 更新“待回答”列表，减去一条（如果列表已经展示的话）
      if (this.anwserListDataArr[1].loaded) {
        let index1 = this.getIndexInList(this.anwserListDataArr[1].list)
        this.anwserListDataArr[1].list.splice(index1, 1)
      }

      // 更新“已回答”列表，增加一条（如果列表已经展示的话）
      if (this.anwserListDataArr[2].loaded) {
        this.anwserListDataArr[2].list.unshift(item)
      }
    },
    showSetPaymentBox () {
      this.setPymentBoxFlag = true
      this.initUserInfoForRaisingQuestion()
    },
    closeSetPaymentBox () {
      this.setPymentBoxFlag = false
    },
    // 修改我的收费
    async submitMyCharge () {
      console.log(88)
      let charge = this.myCharge
      if (JSON.parse(this.isFree)) {
        charge = 0
      } else {
        let reg = /^[0-9]*[1-9][0-9]*$/
        if (!reg.test(this.myCharge)) {
          this.showMsgTip('请输入整数的金额')
          return false
        }
      }
      let res = await setMyAnswereCharge({ answerPay: charge })
      if (res.data) {
        this.showMsgTip('金额设置成功')
        this.closeSetPaymentBox()
      } else {
        this.showMsgTip('金额设置失败')
      }
    },
    showMsgTip (tip) {
      window.layui.layer.msg(tip)
    }
  }
}
</script>
<style lang="scss" scoped>
@import "../../style/res/myquestion";
</style>
